package com.party.mobile.web.controller.photo;

import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.member.Member;
import com.party.core.model.photo.PhotosImgInfo;
import com.party.core.model.photo.PhotosTag;
import com.party.core.service.photo.IPhotosImgInfoService;
import com.party.core.service.photo.IPhotosTagService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.photo.ImgBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.photo.input.ImgUploadInput;
import com.party.mobile.web.dto.photo.output.ImgDetailOutput;
import com.party.mobile.web.dto.photo.output.ImgOutput;
import com.party.mobile.web.dto.photo.output.ImgTimeOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Description: 图片
 * @Author: yangshoukun
 * @Date: 2018/6/5 9:57
 */
@Controller
@RequestMapping(value = "/photos/img")
public class ImgController {
    @Autowired
    private ImgBizService imgBizService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private IPhotosTagService photosTagService;

    @Autowired
    private IPhotosImgInfoService photosImgInfoService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 照片列表
     *
     * @param tagId
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list")
    public AjaxResult list(String tagId, String photosId, Page page) {
        try {
            PhotosTag tag = photosTagService.get(tagId);
            if (null != tag && PhotosTag.ALBUM_TIME_LINE.equals(tag.getName())) {
                List<ImgTimeOutput> list = imgBizService.time(tagId, page);
                return AjaxResult.success(list, page);
            } else {
                List<ImgOutput> list = imgBizService.list(tagId, photosId, page);
                return AjaxResult.success(list, page);
            }
        } catch (BusinessException be) {
            return AjaxResult.error(AjaxResult.ERROR_CODE, be.getMessage());
        } catch (Exception e) {
            logger.error("获取照片列表异常", e);
            return AjaxResult.error();
        }
    }

    /**
     * 时间线的时间列表
     *
     * @param tagId
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/time")
    public AjaxResult time(String tagId, Page page) {
        try {
            List<ImgTimeOutput> list = imgBizService.time(tagId, page);
            return AjaxResult.success(list, page);
        } catch (BusinessException be) {
            return AjaxResult.error(AjaxResult.ERROR_CODE, be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/timeData")
    public AjaxResult timeData(String tagId, String photoId, String time, Page page) {
        try {
            if (StringUtils.isEmpty(tagId) && StringUtils.isEmpty(photoId)) {
                throw new BusinessException("相册分类id不能为空");
            }
            if (StringUtils.isEmpty(time)) {
                throw new BusinessException("时间线time不能为空");
            }
            if (StringUtils.isEmpty(photoId)) {
                PhotosTag tag = photosTagService.get(tagId);
                if (tag == null) {
                    throw new BusinessException("相册id不能为空");
                }
                photoId = tag.getPhotosId();
            }
            if (StringUtils.isEmpty(photoId)) {
                throw new BusinessException("相册id不能为空");
            }
            List<ImgOutput> list = imgBizService.timeData(photoId, time, page);
            return AjaxResult.success(list, page);
        } catch (BusinessException be) {
            return AjaxResult.error(AjaxResult.ERROR_CODE, be.getMessage());
        } catch (Exception e) {
            logger.error("获取时间线数据异常", e);
            return AjaxResult.error();
        }
    }

    /**
     * 验证能不能上传
     *
     * @param memberId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/verify")
    public AjaxResult verify(String memberId, String photosId) {
        try {
            boolean result = imgBizService.verify(memberId, photosId);
            if (result) {
                AjaxResult ajaxResult = new AjaxResult(true);
                ajaxResult.setData(true);
                ajaxResult.setDescription("true");
                return ajaxResult;
            }
            AjaxResult ajaxResult = new AjaxResult(true);
            ajaxResult.setData(false);
            ajaxResult.setDescription("false");
            return ajaxResult;
        } catch (BusinessException be) {
            return AjaxResult.error(AjaxResult.ERROR_CODE, be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    /**
     * 图片上传
     *
     * @param input
     * @param result
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/upload")
    public AjaxResult upload(@Validated ImgUploadInput input, BindingResult result, HttpServletRequest request) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }
        try {
            Member member = currentUserBizService.getMember(request);
            if (null == member || StringUtils.isEmpty(member.getId())) {
                throw new BusinessException("请登录");
            }
            Map<String, Object> imgMap = imgBizService.upload(input, member);
            return AjaxResult.success(imgMap);
        } catch (BusinessException be) {
            return AjaxResult.error(AjaxResult.ERROR_CODE, be.getMessage());
        } catch (Exception e) {
            logger.error("图片上传异常", e);
            return AjaxResult.error();
        }
    }

    /**
     * 移动图片
     *
     * @param tagId:  图片本来的分类(点开图片的地方)
     * @param imgIds: 图片的id, 用英文逗号隔开
     * @param tagIds: 要移动到的分类id, 用英文逗号隔开
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/move")
    public AjaxResult move(String tagId, String imgIds, String tagIds, HttpServletRequest request) {
        try {
            Member member = currentUserBizService.getMember(request);
            if (null == member || StringUtils.isEmpty(member.getId())) {
                throw new BusinessException("请登录");
            }
            boolean r = imgBizService.move(tagId, imgIds, tagIds, member);
            if (r) {
                PhotosImgInfo imgInfo = photosImgInfoService.getImgInfo(imgIds);
                ImgOutput imgOutput = imgBizService.transfromObject(imgInfo);
                return AjaxResult.success(imgOutput);
            }
            return AjaxResult.error();
        } catch (BusinessException be) {
            return AjaxResult.error(AjaxResult.ERROR_CODE, be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    /**
     * 图片详情
     *
     * @param id:    图片id
     * @param tagId: 从哪个分类进入图片详情的
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "detail")
    public AjaxResult detail(String id, String tagId, Integer isCount) {
        try {
            ImgDetailOutput output = imgBizService.detail(id, tagId, isCount);
            return AjaxResult.success(output);
        } catch (BusinessException be) {
            return AjaxResult.error(AjaxResult.ERROR_CODE, be.getMessage());
        } catch (Exception e) {
            logger.error("详情异常", e);
            return AjaxResult.error(100, "详情异常");
        }
    }

    @ResponseBody
    @RequestMapping("initOperate")
    public AjaxResult initOperate() {
        try {
            return AjaxResult.success(imgBizService.initOperate());
        } catch (Exception e) {
            logger.error("初始化照片的操作信息异常", e);
            return AjaxResult.error(100, e.getMessage());
        }
    }

    /**
     * 批量更新浏览次数
     *
     * @param imgIds 相片编号 以,号隔开
     * @return
     */
    @ResponseBody
    @RequestMapping("batchUpdateView")
    public AjaxResult batchUpdateView(String imgIds) {
        try {
            if (StringUtils.isEmpty(imgIds)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "相片编号为空");
            }
            for (String imgId : imgIds.split(",")) {
                PhotosImgInfo photosImgInfo = photosImgInfoService.get(imgId);
                photosImgInfo.setViewNum(photosImgInfo.getViewNum() + 1);
                photosImgInfoService.update(photosImgInfo);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("批量更新浏览次数异常", e);
            return AjaxResult.error(100, "批量更新浏览次数异常");
        }
    }

    /**
     * 删除照片
     *
     * @param imgId: 图片id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult delete(String imgId) {
        try {
            imgBizService.delete(imgId);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("删除照片异常", e);
            return AjaxResult.error(100, "删除照片异常");
        }
    }
}
